<?php

declare(strict_types=1);

namespace App\Service;

/**
 * 商家认证信息附件服务
 * Class FlyShopCertificateAttService
 * @package App\Service
 */
class FlyShopCertificateAttService extends BaseService
{

    /**
     * 保存附件信息
     * @param array $params 附件信息：shop_id cert_id fileinfo_id type(1|2|3|4)
     * @return bool
     */
    public function saveCertAtt(array $params): bool
    {
        $att_fields = ['shop_id', 'fileinfo_id', 'cert_id', 'type'];

        if (!$this->cleanOldAtt($params['shop_id'] ?? 0)) {
            return false;
        }
        $att_data = $params['cert_atts'] ?? [];
        $model = $this->getModelInstance();
        $save_data = [];
        foreach ($att_data as $param) {
            // 保存模型
            if (!is_array($param)) {
                return false;
            }
            $tmp = [];
            foreach ($param as $p_k => $p) {
                if (empty($p)) {
                    return false;
                }
                // 要保存的数据
                if (in_array($p_k, $att_fields)) {
                    $tmp[$p_k] = $p;
                }
            }
            $save_data[] = $tmp;
        }
        // 批量保存
        if (!$model->insert($save_data)) {
            return false;
        }
        return true;
    }

    /**
     * 清除原来绑定的附件信息
     * @param int $shop_id
     * @return bool
     */
    public function cleanOldAtt(int $shop_id): bool
    {
        // 删除原来绑定数据 清除缓存
        return $this->getModelInstance()->query(true)->where(['shop_id' => $shop_id])->delete();
    }


    /**
     * @param int $shop_id
     * @param int|null $cert_type
     * @return array
     */
    public function getCertTypeByCertID(int $shop_id, ?int $cert_type = FlyShopCertificateService::TYPE_LICENSE): array
    {
        $cert = $this->getModelInstance()
            ->with(['with_fileinfo'])
            ->whereHas('with_fileinfo', function ($where) use ($shop_id, $cert_type) {
                $where->where('shop_id', '=', $shop_id);
                if (!empty($cert_type)) {
                    if ($cert_type == FlyShopCertificateService::TYPE_ID) {
                        $where->whereIn('type', [3, 4]);// 身份证
                    } else {
                        $where->where('type', $cert_type);
                    }
                }
            })
            ->where(['shop_id' => $shop_id])
            ->get();
        if (empty($cert)) {
            return [];
        }
        return $cert->toArray();
    }
}